package deepr.src.graph;

import deepr.behaviour.RequestDispose;
import deepr.core.DisposeContext;
import deepr.db.GraphMapper;
import deepr.entity.DeeprInfoResponse;
import deepr.entity.DeeprRequest;
import deepr.entity.DeeprListResponse;
import deepr.lib.*;
import lombok.extern.slf4j.Slf4j;
import org.neo4j.driver.Record;
import org.springframework.stereotype.Component;

import java.util.*;

@Slf4j
@Component
public class GraphDispose implements RequestDispose {

  public <T> DeeprListResponse<T> list(DisposeContext ctx, DeeprRequest deeprRequest) throws Exception {
    String str = GraphQlLib.list((GraphDisposeContext) ctx, deeprRequest);
    log.debug("str: \n{}, params: {}", str, ctx.getFilterParams());
    Record record = ((GraphMapper) ctx.getDeeprMapper()).queryInfo(str, ctx.getFilterParams());
    DeeprListResponse<T> response = new DeeprListResponse<>();
    response.setPage(deeprRequest.getPage());
    if (record == null) {
      response.setList(new LinkedList<>());
      return response;
    }
    List<T> list = Map2Bean.mapToBean(record, deeprRequest.getObject());
    response.setTotalCount(record.get("totalCount").asLong(), deeprRequest.getPageSize());
    response.setList(list);
    response.setObject(deeprRequest.getObject());
    return response;
  }

  public <T> DeeprInfoResponse<T> info(DisposeContext ctx, DeeprRequest deeprRequest) throws Exception {
    String str = GraphQlLib.info((GraphDisposeContext) ctx, deeprRequest);
    log.debug("str: {}\n, params: {}", str, ctx.getFilterParams());
    Record record = ((GraphMapper) ctx.getDeeprMapper()).queryInfo(str, ctx.getFilterParams());
    DeeprInfoResponse<T> response = new DeeprInfoResponse<>();
    response.setObject(deeprRequest.getObject());
    if (record == null) {
      return response;
    }
    List<T> list = Map2Bean.mapToBean(record, deeprRequest.getObject());
    if (list.size() == 0)
      return response;
    response.setInfo(list.get(0));
    return response;
  }

}
